//详情页面
import '@/style/markdown.css'
import { useEffect, useState, useRef } from 'react'
import { useParams, useNavigate } from "react-router-dom";
import { articleDetail, articleRecommend } from '@/api/article';
import { formatHTMLAddCopyBtn } from '@/utils/utils'
import _ from 'lodash' //防抖
import BaseCard from 'coms/baseCard';
import style from './style.module.less'

//评论组件
// import BaseComment from 'coms/baseComment';
//商店
// import { useStore } from "@/store/Provider"
//antd组件
// import { message } from "antd"

const ArticleDetailView = () => {
  const { id } = useParams(); //获取详情数据的id
  const navigate = useNavigate()
  const [detailInfo, setDetail] = useState([]);//楼层
  const [flowIndex, setFlowIndex] = useState(0);
  const markDownRef = useRef(null);
  // const { commentModule } = useStore();
  const changeDetaiil = (ids) => {
    navigate(`/article/${ids}`)
  }
  const handleClickFlow = ({ index, item }) => {
    setFlowIndex(index); //改变楼层
    const titleTag = document.getElementById(item.id);
    console.log(titleTag.offsetTop);
    document.documentElement.scrollTo(0, titleTag.offsetTop);
  }
  useEffect(() => {
    articleDetail(id).then((res) => {
      const data = res.data.data;
      data.html = formatHTMLAddCopyBtn(data.html);
      data.toData = JSON.parse(data.toc);
      setDetail(data);
      // eslint-disable-next-line no-console
    })
  }, [detailInfo])
  useEffect(() => {
    if (detailInfo?.toData?.length) {
      const offsetTops = detailInfo.toData.map(item => {
        const el = document.getElementById(item.id);
        return {
          el: el,
          offsetTop: el.offsetTop
        }
      })
      //监听滚动事件
      window.addEventListener('scroll', window.scrollEvent = _.debounce(() => {
        const scrollTop = document.documentElement.scrollTop;
        let curIndex = 0;
        offsetTops.forEach(({ offsetTop }, i) => {
          if (i === offsetTops.length - 1 && scrollTop > offsetTop) {
            curIndex = i
            return;
          }
          if (scrollTop >= offsetTop && scrollTop < offsetTops[i + 1].offsetTop) {
            curIndex = i
          }
        })
        //修改楼层id
        setFlowIndex(curIndex);
      }, 100))
    }
    return () => { //卸载滚动事件
      window.removeEventListener('scroll', window.scrollEvent);
    }
  }, [markDownRef, detailInfo])

  return (
    <div style={{ paddingLeft: "5%" }}>
      {/* 详情内容 */}
      <div className={style.left}>
        <p><img src={detailInfo.cover} alt="" width={"100%"} height={420} /></p>
        <div className={style.detitle}>
          <h1>{detailInfo.title}</h1>
          <p>发布于{detailInfo.publishAt}.阅读量{detailInfo.views}</p>
        </div>
        <div
          className="markdown"
          dangerouslySetInnerHTML={{ __html: detailInfo?.html }}
          ref={markDownRef}>
        </div>
      </div>
      <div className="card">
        <BaseCard title="推荐阅读"
          request={async () => {
            const { data: { data } } = await articleRecommend(id);
            // eslint-disable-next-line no-console
            console.log(data, 're');
            return {
              data
            }
          }}
        >
          {
            (item, index) => {
              return <p key={index} onClick={() => changeDetaiil(item.id)}>{item.title}</p>
            }
          }
        </BaseCard>
        {/* 目录 */}
        <div className="catalogue">
          <h2>目录</h2>
          <ul>
            {
              Array.isArray(detailInfo?.toData) && detailInfo.toData.map((item, index) => {
                return <li
                  onClick={() => handleClickFlow({ index, item })}
                  className={flowIndex === index ? style.active : ''}
                  style={{ paddingLeft: (item.level - 1) * 10, cursor: 'pointer' }}
                  key={item.id}>{item.text}</li>
              })
            }
          </ul>
        </div>
      </div>

      {/* 评论组件 */}
      {/* <BaseComment
        pageInfo={{ // 启用分页
          page: 1,
          pageSize: 3,
          size: 'small'
        }}
        request={async ({ pageConfig }) => {  // 发送请求 组件创建 分页改变
          const { data } = await commentModule.getCommentList(id, pageConfig);
          return {
            data: data[0], // 当前页数据
            total: data[1]  // 总条数
          }
        }}
      /> */}

    </div >
  )
}
export default ArticleDetailView